package freezzz.server.EventDriver;

import freezzz.client.EventWidget.EventType;
import freezzz.client.EventWidget.TimelineEvent;
import freezzz.server.TestServiceImpl;
import winterwell.jtwitter.Twitter;

import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;

/**
 * Created by Ivan Litsvinenka e Emanuele Ricci
 * Date: 27-ago-2009
 * Time: 23.32.32
 */
public class DriverTwitterEvents extends EventsDriver {
    private Twitter twitter;
    private static Hashtable<Date, ArrayList<TimelineEvent>> eventsCash = new Hashtable<Date, ArrayList<TimelineEvent>> ();


    public DriverTwitterEvents () {
        twitter = new Twitter ( "eventstimeline", "148148" );
        populateCache ();
    }

    private void populateCache () {
        int page = 1;
        boolean done = false;
        ArrayList<Twitter.Status> tmp;
        while ( !done ) {
            twitter.setPageNumber ( page );
            tmp = new ArrayList<Twitter.Status> ( twitter.getUserTimeline ( "freezzz" ) );
            if ( tmp.size () == 0 ) done = true;
            for ( Twitter.Status twstatus : tmp ) {
                Date createdDateKey = TestServiceImpl.getDayDate ( twstatus.createdAt );
                TimelineEvent tmpEvent = new TimelineEvent ( twstatus.getCreatedAt (), twstatus.getUser ().getName (), twstatus.getText (), new EventType ( "Twitter", "res/icons/twitter.png" ) );

                if ( eventsCash.containsKey ( createdDateKey ) ) {
                    if ( !eventsCash.get ( createdDateKey ).contains ( tmpEvent ) ) {
                        System.out.println ( "New event for date" + createdDateKey );
                        eventsCash.get ( createdDateKey ).add ( tmpEvent );
                    }
                } else {
                    System.out.println ( "New date with events" );
                    eventsCash.put ( createdDateKey, new ArrayList<TimelineEvent> () );
                    eventsCash.get ( createdDateKey ).add ( tmpEvent );
                }
            }
            page++;
        }
    }

    public ArrayList<TimelineEvent> getEventsForDate ( Date date ) {
        ArrayList<TimelineEvent> result = new ArrayList<TimelineEvent> ();
        date = TestServiceImpl.getDayDate ( date );

        if ( eventsCash.containsKey ( date ) ) {
            return eventsCash.get ( date );
        }
        return result;
    }

}
